package com.ews.onlineexchange.controller;

import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.Notification;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.EntityQuery;
import com.ews.onlineexchange.service.UserService;

@Model
public class NotificationList extends EntityQuery<Notification> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	UserService userService;
	
	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<Notification> entity) {
		List<Predicate> restrictions = super.getRestrictions( cb, entity );
		User user = userService.getLoginedUser();

		Join<Notification, User> loginedUser = entity.join( "receiver" );
		if ( user == null ) {
			restrictions.add( cb.equal( loginedUser.get( "id" ), "" ) );
		} else {
			restrictions.add( cb.equal( loginedUser.get( "id" ), user.getId() ) );
		}

		restrictions.add( cb.equal( entity.get( "delFlag" ), DataEntity.DEL_FLAG_NORMAL ) );
		String title = (String) getParameterValues().get( "title" );
		if ( StringUtils.isNotBlank( title ) ) {
			restrictions.add( cb.like( entity.get( "titile" ), getStringRestriction( title ) ) );
		}
		return restrictions;
	}

	public NotificationList() {
		setMaxResults(MAX_RESULTS_FEW);
		setOrder("sendDate desc");
	}

	

}
